package main

import (
	"net/http"

	"github.com/julienschmidt/httprouter"
)

// middleWareHandler 中间转件转换层
type middleWareHandler struct {
	r *httprouter.Router // 路由
	l *ConnLimiter       // 流控
}

// NewMiddleWareHandler 创建 middleWareHandler
func NewMiddleWareHandler(r *httprouter.Router, cc int) http.Handler {
	m := middleWareHandler{}
	m.r = r
	m.l = NewConnLimiter(cc) // 调用初始化限流令牌
	return m
}

// 定义一个 ServeHTTP 来做拦截层
// 会自动调用这个 ServeHTTP 函数，相当于重写原来的 http.Handler 里面的 ServeHTTP 函数
func (m middleWareHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if !m.l.GetConn() {
		sendErrorResponse(w, http.StatusTooManyRequests, "限制请求连接数！")
		return
	}

	// 把请求往下传,也就是放行
	m.r.ServeHTTP(w, r)

	defer m.l.ReleaseConn()
}

// RegisterHandlers 注册 handler
func RegisterHandlers() *httprouter.Router {
	router := httprouter.New()

	router.GET("/videos/:vid-id", streamHandler)
	router.POST("/upload/:vid-id", uploadHandler)

	return router

}

func main() {

	r := RegisterHandlers()
	mh := NewMiddleWareHandler(r, 2)
	http.ListenAndServe(":9000", mh)

}
